var config = require('../../script/config');
var orderApi = require('../../script/order.js');
var publicApi = require('../../script/public.js');
// var QQMapWX = require('../../qqmap/qqmap-wx-jssdk');
// var qqmapsdk;
Page({
  /**
   * 页面的初始数据
   */
  data: {
    pickShow: false,
    CommonParam: '',
    input_timeOut: null,
    userinfo: null,
    pagination: {
      page: 1,
      rows: 4,
      sidx: '',
      sord: ''
    },
    count: 0,
    orderList: [],
    canLoadData: true,
    userList: [],
    currentOrder: null,
    dispatcher: null,
    noData: false,
    isReachBottom: false,
    /******分派弹窗**** */
    showPage: false,
    deptIndex: 0,
    deptList: [],
    stationList: [],
    stationIndex: 0,
    operList: [],
    HandleDeptNo: '',
    isShowConfirm: false,
    HuiTui: '',
    /******转派******** */
    isSelectLastNode: true,
    showPopup: false,
    TranspondData: {
      OrderID: '',
      RepairDept: '',
      ProcedureCode: '',
      AssignDeptNo: ''
    },
    dataTree: [],
  },
  _refreshData: function () {
    this.setData({ //初始化数据
      pagination: {
        page: 1,
        rows: 4,
        sidx: '',
        sord: ''
      },
      count: 0,
      // orderList: [],
      canLoadData: true,
      userList: [],
      currentOrder: null,
      dispatcher: null,
      noData: false,
      isReachBottom: false,
      showPage: false,
      deptIndex: 0,
      deptList: [],
      stationList: [],
      stationIndex: 0,
      operList: [],
      operIndex: -1,
      HandleDeptNo: '',
      isShowConfirm: false,
      HuiTui: '',
      showPopup: false,
      TranspondData: {
        OrderID: '',
        RepairDept: '',
        ProcedureCode: '',
        AssignDeptNo: ''
      },
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // qqmapsdk = new QQMapWX({
    //   key: config.mapKey
    // });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getUserInfo()
    this._refreshData();
    this.getOrderList(true)
    this.GetDeptListTree();
    // this.getDeptTree()
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.showNavigationBarLoading();
    this._refreshData();
    this.getOrderList(true);
    this.GetDeptListTree();
    wx.hideNavigationBarLoading();
    wx.stopPullDownRefresh();
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.setData({
      isReachBottom: true
    });
    if (this.data.canLoadData) {
      this.setData({
        'pagination.page': this.data.pagination.page + 1
      })
      this.getOrderList();
    } else {
      wx.showToast({
        title: '没有更多数据了',
        icon: 'none',
        duration: 1000
      });
    }
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {},
  //   searchFocus: function (e) {
  //     wx.navigateTo({
  //         url: "../search/search"
  //     })
  // },
  call: function (e) {
    var pnonenum = e.currentTarget.dataset.phone
    var res = wx.getSystemInfoSync();
    if (res.platform == 'ios') {
      wx.makePhoneCall({
        phoneNumber: pnonenum
      });
    } else {
      wx.showActionSheet({
        itemList: [pnonenum, '呼叫'],
        success: function (res) {
          if (res.tapIndex == 1) {
            wx.makePhoneCall({
              phoneNumber: pnonenum
            })
          }
        }
      })
    }
  },
  getUserInfo: function () {
    try {
      var value = wx.getStorageSync(config.storageKey.userinfo)
      if (value) {
        this.setData({
          userinfo: value
        })
      }
    } catch (e) {
      // Do something when catch error
    }
  },
  inputChange(e) {
    let {
      input_timeOut
    } = this.data
    if (input_timeOut) {
      clearTimeout(input_timeOut)
    }
    input_timeOut = setTimeout(() => {
      this.setData({
        CommonParam: e.detail.value
      })
      this._refreshData();
      this.getOrderList(true)
    }, 300);
    this.setData({
      input_timeOut
    }) // 计时器
  },
  getOrderList(isRefresh) {
    wx.showLoading({
      title: '加载中',
      mask: true
    })
    let params = {
      pagination: this.data.pagination,
      queryParam: {
        WxStatus: "1", //微信工单状态 1-待分派 2-待接收 3-待执行 31-待执行的二次派单 32-待执行的催办 33-超时 34-紧急
        IsFinish: false,
        CommonParam: this.data.CommonParam
      }
    };
    orderApi.GetOrderList(params).then(res => {
      if (res.code === 200) {
        let dataList = []
        if (isRefresh) {
          dataList = [...res.data.Items]
        } else {
          dataList = [...this.data.orderList, ...res.data.Items]
        }
        let canLoadData = res.data.HasNextPages
        const noData = dataList.length === 0
        this.setData({
          orderList: dataList,
          count: res.data.TotalCount,
          canLoadData: canLoadData,
          noData: noData
        })
      }
      wx.hideLoading();
    }).catch(_err => {
      wx.hideLoading();
    });
  },
  getDeptTree() {
    publicApi.GetRepairDeptListTree().then(res => {
      if (res.code === 200) {
        this.setData({
          deptList: res.data
        })
      }
    })
  },
  // toMap(e) {
  //   var info = e.currentTarget.dataset.info
  //   qqmapsdk.geocoder({
  //     address: info.Address,
  //     success: res =>{
  //       wx.openLocation({
  //         latitude: res.result.location.lat,
  //         longitude: res.result.location.lng,
  //         scale: 18
  //       })
  //     }
  //   })
  //   // wx.getLocation({
  //   //   type: 'gcj02', //返回可以用于 wx.openLocation 的经纬度
  //   //   success(res) {
  //   //     const latitude = res.latitude
  //   //     const longitude = res.longitude
  //   //     wx.openLocation({
  //   //       latitude,
  //   //       longitude,
  //   //       address: info.Address,
  //   //       scale: 18
  //   //     })
  //   //   }
  //   // })
  // },
  async showPage(e) {
    const res = await publicApi.GetRepairDeptListTree();
    if (res.code === 200) {
      this.setData({
        deptList: res.data
      })
      const order = e.currentTarget.dataset.order;
      let HandleDeptNo = order.AssignDeptNo;
      let deptIndex = 0;
      let stationIndex = 0;
      if (this.data.deptList.length > 0) {
        for (let i = 0; i < this.data.deptList.length; i++) {
          const dept = this.data.deptList[i]
          if (dept.DEPT_NO === HandleDeptNo) {
            deptIndex = i;
            stationIndex = 0;
            break;
          } else {
            for (let j = 0; j < dept.MODELLIST.length; j++) {
              if (dept.MODELLIST[j].DEPT_NO === HandleDeptNo) {
                deptIndex = i;
                stationIndex = j;
                break;
              }
            }
          }
        }
      }
      this.setData({
        stationList: this.data.deptList.length > 0 ? this.data.deptList[deptIndex].MODELLIST : [],
        deptIndex: deptIndex,
        stationIndex: stationIndex
      })
      if (this.data.stationList.length > 0) {
        HandleDeptNo = this.data.stationList[stationIndex].DEPT_NO
      }
      this.setData({
        showPage: true,
        currentOrder: order,
        HandleDeptNo: HandleDeptNo
      });
      this.queryOperList();
    }
  },
  leave() {
    this.setData({
      showPage: false,
      stationIndex: 0,
      deptIndex: 0
      // operList: []
    });
  },
  getStation(e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      deptIndex: index,
      stationIndex: 0,
      stationList: this.data.deptList[index].MODELLIST
    })
    if (this.data.deptList[index].MODELLIST.length > 0) {
      this.setData({
        HandleDeptNo: this.data.deptList[index].MODELLIST[0].DEPT_NO
      })
      this.queryOperList();
    } else {
      this.setData({
        operList: []
      })
    }
  },
  getOper(e) {
    const station = e.currentTarget.dataset.station
    this.setData({
      stationIndex: e.currentTarget.dataset.index,
      HandleDeptNo: station.DEPT_NO
    })
    this.queryOperList()
  },
  queryOperList() {
    const params = {
      data: {
        pagination: {
          rows: 9999,
          page: 1,
          sidx: '',
          sord: ''
        },
        queryJson: JSON.stringify({
          DEPT_NO: this.data.HandleDeptNo,
          CUR_STATUS_CODE: '01',
          ONLY_DEPT_NO: '1'
        })
      }
    }
    publicApi.GetUser(params).then(res => {
      if (res.code === 200) {
        this.setData({
          operList: res.data.Items
        })
      }
    });
  },
  selectOper(e) {
    const _this = this;
    const oper = e.currentTarget.dataset.oper;
    wx.showModal({
      title: '提示',
      content: '确定分派给' + oper.USER_NAME + '？',
      success(res) {
        if (res.confirm) {
          _this.setData({
            operIndex: e.currentTarget.dataset.index
          })
          setTimeout(() => {
            const oper = e.currentTarget.dataset.oper
            _this.setData({
              showPage: false,
              dispatcher: oper
            })
            _this.doDispitch()
          }, 1000)
        }
      }
    })
  },
  doDispitch() {
    const _this = this
    const params = {
      OrderID: this.data.currentOrder.OrderID,
      ProcedureCode: this.data.currentOrder.ProcedureCode,
      ProcedureStatus: 2,
      NextReceiverNo: this.data.dispatcher.USER_NO,
      HandleWay: 1,
      HandleDeptNo: this.data.HandleDeptNo
    }
    orderApi.UpdateOrderProcedure(params).then(res => {
      if (res.code === 200) {
        this.setData({
          operIndex: -1
        })
        wx.showToast({
          title: res.info,
          icon: 'success',
          duration: 2000,
          success: function () {
            _this._refreshData();
            _this.getOrderList(true);
            // _this.getDeptTree()
          }
        })
      }
    })
  },
  back: function (e) {
    var that = this;
    const order = e.currentTarget.dataset.order
    // if(order.TicketPhones.length === 0 && order.Status === '01' && order.ProcedureCode === '01'){
    //   wx.showToast({
    //     title: '没有服务单不能回退！',
    //     icon: 'none',
    //     duration: 2000
    //   });
    //   return;
    // }
    wx.showModal({
      content: '是否确定回退该工单？',
      success(res) {
        if (res.confirm) {
          that.setData({
            isShowConfirm: true,
            currentOrder: order
          })
        }
      }
    })
  },
  //输入框中的值
  setValue: function (e) {
    this.setData({
      HuiTui: e.detail.value
    })
  },
  //点击取消按钮
  cancel: function () {
    var that = this
    that.setData({
      isShowConfirm: false,
    })
  },
  //点击确认按钮
  confirmAcceptance: function () {
    var that = this;
    if (that.data.HuiTui == '') {
      wx.showToast({
        title: '回退原因不能为空！',
        icon: 'none',
        duration: 2000
      })
      return;
    }
    that.setData({
      isShowConfirm: false,
    })
    wx.showLoading({
      mask: true,
      title: '回退处理中...'
    });
    const params = {
      OrderID: that.data.currentOrder.OrderID,
      ProcedureCode: that.data.currentOrder.ProcedureCode,
      ProcedureStatus: 3,
      HandlerResult: that.data.HuiTui,
      HandleWay: 1
    }
    orderApi.UpdateOrderProcedure(params).then(res => {
      if (res.code === 200) {
        wx.showToast({
          title: res.info,
          icon: 'success',
          duration: 4000,
          success: function () {
            that._refreshData();
            that.getOrderList(true);
            // that.getDeptTree()
          }
        })
      } else {
        wx.showToast({
          title: res.info,
          icon: 'error',
          duration: 2000
        })
      }
    })
  },
  /*******转派********/
  GetDeptListTree() {
    publicApi.GetDeptListTree({ typeCode: '06,07'}).then(res => {
      if (res.code === 200) {
        this.setData({
          dataTree: res.data[0].MODELLIST
        })
      }
    })
  },
  showPopup: function (e) {
    const item = e.currentTarget.dataset.item;
    this.setData({
      showPopup: true,
      "TranspondData.OrderID": item.OrderID,
      "TranspondData.ProcedureCode": item.ProcedureCode
    });
  },
  ClosePopup() {
    this.setData({
      showPopup: false,
      "TranspondData.OrderID": '',
      "TranspondData.ProcedureCode": '',
      "TranspondData.AssignDeptNo": ''
    });
  },
  handleSelect(e) {
    // console.log(e);
    if (e.detail.tips) {
      console.log('必须选择到最后一个节点');
    } else {
      this.setData({
        'TranspondData.AssignDeptNo': e.detail.item.DEPT_NO
      });
    }
  },
  DoTrans() {
    const _this = this;
    if (_this.data.TranspondData.AssignDeptNo === '') {
      wx.showToast({
        title: '请选择转派部门！',
        icon: 'none',
        duration: 2000
      });
      return;
    };
    _this.setData({
      showPopup: false
    });
    wx.showLoading({
      title: '数据加载中',
      mask: true
    });
    const params = {
      OrderID: _this.data.TranspondData.OrderID,
      ProcedureCode: _this.data.TranspondData.ProcedureCode,
      ProcedureStatus: 4,
      AssignDeptNo: _this.data.TranspondData.AssignDeptNo,
      HandleWay: 1
    }
    orderApi.UpdateOrderProcedure(params).then(res => {
      if (res.code === 200) {
        const _this = this;
        _this._refreshData();
        wx.showToast({
          title: res.info,
          icon: 'success',
          duration: 2000,
          success: function () {
            setTimeout(() => {
              _this.getOrderList(true);
            }, 2000)
          }
        });
      } else {
        wx.showToast({
          icon: 'none',
          title: res.info,
          duration: config.toast.duration
        });
      }
    }).catch(_err => {
      wx.hideLoading();
    });
  },
})